package com.oasistudio.ads.expert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.oasistudio.ads.expert.banner.AdViewAdwo;
import com.oasistudio.ads.expert.banner.AdViewAiwan;
import com.oasistudio.ads.expert.banner.AdViewAppMedia;
import com.oasistudio.ads.expert.banner.AdViewCasee;
import com.oasistudio.ads.expert.banner.AdViewDomob;
import com.oasistudio.ads.expert.banner.AdViewGoogle;
import com.oasistudio.ads.expert.banner.AdViewSmartmad;
import com.oasistudio.ads.expert.banner.AdViewTaobao;
import com.oasistudio.ads.expert.banner.AdViewVpon;
import com.oasistudio.ads.expert.banner.AdViewWiyun;
import com.oasistudio.ads.expert.banner.AdViewYoumi;

import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SelectUnion extends ListActivity {
	
	private static List<String> UNION_NAMES = new ArrayList<String>();
	
	private class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return UNION_NAMES.size();
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return UNION_NAMES.get(position);
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.union_list_item, null);
                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.unionCheckBox = (CheckBox) convertView.findViewById(R.id.union_checkbox);
                holder.unionCheckBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						if(isChecked){
							selectedUnions.add(buttonView.getTag().toString());
						}else{
							selectedUnions.remove(buttonView.getTag().toString());
						}
					}
                	
                });
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            String unionName = UNION_NAMES.get(position);
            holder.unionCheckBox.setTag(unionName);
			holder.unionCheckBox.setText((position+1)+". "+unionName);
			if(selectedUnions.contains(unionName)){
				holder.unionCheckBox.setChecked(true);
			}
            return convertView;
        }

        class ViewHolder {
            CheckBox unionCheckBox;
        }
    }

	private Set<String> selectedUnions = new HashSet<String>();

    public void confirm(View view) {
		System.out.println("-----------------------selectedUnions="+selectedUnions);
		this.saveCheckedUnion();
    	this.finish();
    }
    
    //设置好联盟选择项后，存起来
	private void saveCheckedUnion(){
		SharedPreferences settings = this.getSharedPreferences(SelectUnion.class.getName(), MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();  
		String unionsSelected = this.selectedUnions.toString().replace("[", "").replace("]", "");
		System.out.println("-----------------------save unionsSelected = "+unionsSelected);
		editor.putString("unionsSelected", unionsSelected);
		editor.commit();
	}
	private void loadCheckedUnion() {
		SharedPreferences settings = getSharedPreferences(SelectUnion.class.getName(), MODE_PRIVATE);
		String unionsSelected = settings.getString("unionsSelected", null);
		System.out.println("-----------------------load unionsSelected = "+unionsSelected);
		if (unionsSelected != null){
			for(String union : unionsSelected.split(",")){
				this.selectedUnions.add(union.trim());
			}
		}
	}

    
	static {
		UNION_NAMES.add(AdViewAdwo.UNION);
		UNION_NAMES.add(AdViewAppMedia.UNION);
		UNION_NAMES.add(AdViewCasee.UNION);
		UNION_NAMES.add(AdViewDomob.UNION);
		UNION_NAMES.add(AdViewGoogle.UNION);
		UNION_NAMES.add(AdViewSmartmad.UNION);
		UNION_NAMES.add(AdViewTaobao.UNION);
		UNION_NAMES.add(AdViewVpon.UNION);
		UNION_NAMES.add(AdViewWiyun.UNION);
		UNION_NAMES.add(AdViewYoumi.UNION);
		UNION_NAMES.add(AdViewAiwan.UNION);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.union_list);
		//System.out.println("...........................AutoReading.onCreate() ");
		//System.out.println("words.size() = "+words.size());
		if(UNION_NAMES.size() < 1){
			displayMessage("没有联盟可选。");
			return;
		}
		this.loadCheckedUnion();
        setListAdapter(new EfficientAdapter(this));
        //final ListView listView = getListView();
        //listView.setItemsCanFocus(false);
        //listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}
	
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG*2);
		t1.show();
	}
}